﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor.Utils
{
    /// <summary>
    /// 此类中的方法改造自：https://www.cnblogs.com/SeNaiTes/p/10701229.html
    /// </summary>
    class LDirectory
    {
        /// <summary>
        /// 文件夹下所有内容copy
        /// </summary>
        /// <param name="srcDirectoryPath">要Copy的文件夹</param>
        /// <param name="destDirectoryPath">要复制到哪个地方</param>
        /// <param name="overwriteExisting">是否覆盖</param>
        /// <returns></returns>
        public static bool CopyDirectory(string srcDirectoryPath, string destDirectoryPath, bool overwriteExisting)
        {
            bool ret = false;
            try
            {
                srcDirectoryPath = srcDirectoryPath.EndsWith(@"\") ? srcDirectoryPath : srcDirectoryPath + @"\";
                destDirectoryPath = destDirectoryPath.EndsWith(@"\") ? destDirectoryPath : destDirectoryPath + @"\";

                if (Directory.Exists(srcDirectoryPath))
                {
                    if (Directory.Exists(destDirectoryPath) == false)
                        Directory.CreateDirectory(destDirectoryPath);

                    foreach (string fls in Directory.GetFiles(srcDirectoryPath))
                    {
                        FileInfo flinfo = new FileInfo(fls);
                        var destFilePath = destDirectoryPath + flinfo.Name;
                        if (overwriteExisting == false)
                        {
                            if (File.Exists(destFilePath) == false)
                            {
                                flinfo.CopyTo(destFilePath, overwriteExisting);
                            }
                        }
                        else
                        {
                            if (File.Exists(destFilePath))
                            {
                                File.Delete(destFilePath);
                            }
                            flinfo.CopyTo(destFilePath, overwriteExisting);
                        }
                    }

                    foreach (string drs in Directory.GetDirectories(srcDirectoryPath))
                    {
                        DirectoryInfo drinfo = new DirectoryInfo(drs);
                        if (CopyDirectory(drs, destDirectoryPath + drinfo.Name, overwriteExisting) == false)
                            ret = false;
                    }
                }
                ret = true;
            }
            catch (Exception ex)
            {
                ret = false;
            }
            return ret;
        }
    }
}
